package com.baizhi.config;

import com.baizhi.realm.AuthorRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //配置过滤器工厂
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置过滤器的规则
        // 配置拦截规则 哪些页面拦截 哪些不拦截 过滤器链
        Map map = new HashMap();
        /*** anon 代表匿名可访问 就是不用登录就可以访问
         * ** authc 代表登录后才能访问 ** 支持通配符*
         * ** 注意拦截规则 一个一个配置 */
        map.put("/login.jsp","anon");
        map.put("/admin/*","anon");

        map.put("/main.jsp", "authc");

        map.put("/menu/*", "authc");
        map.put("/jsp/*", "authc");
        System.out.println("shiro自带拦截器以执行");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);


        //设置一个安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor; }
    /*** 创建安全管理器
     * * @Bean 方法的形参 如果对应的类型的对象在工厂中有 会自动装配上 * @return
     */
    @Bean
    public SecurityManager getSecurityManager(AuthorRealm authorRealm){
        DefaultWebSecurityManager defaultSecurityManager=new DefaultWebSecurityManager();
        //设置realm
        defaultSecurityManager.setRealm(authorRealm);
        return defaultSecurityManager;
    }

    /*** 创建Realm
     * @return *
     */
    @Bean
    public AuthorRealm authenticatingRealm(){
        return new AuthorRealm();
    }

    /**
     *  开启shiro aop注解支持
     *  使用代理方式;所以需要开启代码支持;否则@RequiresRoles等注解无法生效
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


}
